package com.imooc.component;

import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.UUID;

/**
 * 发送者
 *
 * @author: 顾志杰
 */
@Component
public class RabbitSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 确认消息的回调监听接口用于确认消息是否被broker所收到
     *
     * @param correlationData 作为唯一标识
     * @param b broker是否落盘成功
     * @param s 失败的一些异常信息
     */
    final RabbitTemplate.ConfirmCallback confirmCallback = (correlationData, b, s) -> {
        System.out.println("消息ACK结果："+ b +",correlationData:" + correlationData.getId());
    };

    /**
     * 对外发送消息方法
     *
     * @param message    具体的消息内容
     * @param properties 额外的附加属性
     * @throws Exception
     */
    public void send(Object message, Map<String, Object> properties) throws Exception {
        /*对附加属性额外封装 MessageHeaders是org.springframework.messaging.MessageHeaders*/
        MessageHeaders mhs = new MessageHeaders(properties);
        /*具体的发送消息 MessageBuilder是org.springframework.messaging.support.MessageBuilder*/
        Message<?> msg = MessageBuilder.createMessage(message, mhs);
        /*消息模式发消息之前需要做监听*/
        rabbitTemplate.setConfirmCallback(confirmCallback);
        /*业务唯一标记*/
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());

        /*发消息*/
        rabbitTemplate.convertAndSend(
                /*具体交换机是什么*/
                "exchange-1",
                /*路由key*/
                "springboot.rabbit",
                /*发送的消息*/
                msg,
                /*发送完成后回调函数*/
                message1 -> {
                    System.err.println("---> post to do: " + message1);
                    return message1;
                },
                correlationData
        );


    }
}
